package com.flex.reflection.proxy;

import javassist.*;

import java.io.IOException;
import java.security.ProtectionDomain;

/**
 * @author ganlt
 * @since 2019/09/23 16:14
 */
public class DyNamicModifyMethod {

    /**
     * 动态修改方法
     */
    public static void modifyBeforeMethod(Class clazz,String method, String content) {
        ClassPool pool = ClassPool.getDefault();
        try {
            CtClass ct = pool.getCtClass(clazz.getName());
            if (ct.isFrozen()) {
                ct.defrost();
            }
            CtMethod m = ct.getDeclaredMethod(method);
            m.insertBefore(content);

            ct.writeFile();
        }  catch ( NotFoundException | CannotCompileException  | IOException e) {
            e.printStackTrace();
        }
    }

    public static void modifyAfterMethod(Class clazz,String method, String content) {
        ClassPool pool = ClassPool.getDefault();
        try {
            CtClass ct = pool.getCtClass(clazz.getName());
            if (ct.isFrozen()) {
                ct.defrost();
            }
            CtMethod m = ct.getDeclaredMethod(method);
            m.insertAfter(content,true);

            ct.writeFile();
        }  catch ( NotFoundException | CannotCompileException  | IOException e) {
            e.printStackTrace();
        }
    }

    public static void addMethod(Class clazz) {
        ClassPool pool = ClassPool.getDefault();
        try {
            CtClass ct = pool.getCtClass(clazz.getName());
            if (ct.isFrozen()) {
                ct.defrost();
            }
            CtMethod ctMethod = CtMethod.make("public void sss(){}",ct);
            ct.addMethod(ctMethod);

            ct.writeFile();
        }  catch ( NotFoundException | CannotCompileException  | IOException e) {
            e.printStackTrace();
        }
    }

    public static Class getNewClass(Class clazz,ClassLoader classLoader) {
        try {
            return Class.forName(clazz.getName(),true,classLoader);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return clazz;
        }
    }

}
